# -*- coding: utf-8 -*-
# @Time    : 2021/11/24 13:23 
# @Author  : BrandonGT
# @FileName: install.py 
# -----------------------------------------------------
# Python 自带Module
import os
import sys
import shutil
import importlib
from getpass import getuser

# Python 第三方Module
import yaml

# Python 自定义Module

# -----------------------------------------------------
CONFIG = os.getcwd()[::-1].split('\\', 1)[-1][::-1] + "\\config\config.yaml"
with open(CONFIG, "r", encoding="utf-8") as content:
    _config = yaml.load(content, Loader=yaml.Loader)


def env_add(fpath):
    """添加临时环境"""
    sys.path.insert(0, fpath)


def env_delete(fpath):
    """删除临时环境"""
    if sys.path[0] == fpath:
        del sys.path[0]


def get_version(fpath):
    """获取版本信息"""
    env_add(fpath)
    import package
    importlib.reload(package)
    version = package._data['version']
    env_delete(fpath)

    return version


def install_package(fpath="", clean=False, location="local"):
    """发布package"""
    if fpath:
        print("执行安装Package中...")
        process = 1  # 执行：1 错误：0
        software = fpath.replace("\\", "/").split("/")[-1]  # 获取软件名
        # package_root = f"{fpath}/package.py"
        version = get_version(fpath)

        print(f"待安装package：{fpath}")
        if location == 'local':
            build_dir = eval(_config.get("Launcher").get("package_local_path")) + f"{software}/{version}"
            print(f"拷贝文件至安装路径：{build_dir}")
        elif location == 'server':
            build_dir = eval(_config.get("Launcher").get("package_network_path")) + f"{software}/{version}"
            print(f"拷贝文件至安装路径：{build_dir}")
        else:
            process = 0
            print("Wrong Argument！")

        if clean:
            try:
                shutil.rmtree(build_dir)
                print("执行清洁安装模式...")
            except FileNotFoundError:
                pass

        if process:
            try:
                shutil.copytree(
                    os.path.join(fpath),
                    os.path.join(build_dir),
                    ignore=shutil.ignore_patterns("*.pyc", "__pycache__")
                )
                print("安装已完成...")
            except FileExistsError:
                print("安装失败！路径已存在，如需覆盖请使用清洁安装模式")

    else:
        print("请指定需要安装的package路径")


if __name__ == '__main__':
    package_path = r"C:\Git_Repo\bd_dcc_launcher_packages\maya2020"
    install_package(fpath=package_path, location='server', clean=True)